package com.tanhua.dubbo.server.api.mongo;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Album;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.TimeLine;
import com.tanhua.domain.vo.Movements;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.server.mapper.UserInfoMapper;
import com.tanhua.dubbo.server.utils.IdService;
import com.tanhua.dubbo.server.utils.RelativeDateFormat;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoMapper infoMapper;

    @Autowired
    private IdService idService;

    private static String albumDbName="quanzi_album_";

    private static String timelineDbName="quanzi_time_line_";

    @Override
    public void save(Publish publish) {
        //1、保存到publish中
        publish.setId(ObjectId.get());
        publish.setPid(idService.getNextId("publish"));
        publish.setCreated(System.currentTimeMillis());
        mongoTemplate.save(publish);

        //2、写入到自己的动态表中
        Album album = new Album();
        album.setPublishId(publish.getId());//动态id
        album.setId(ObjectId.get());
        album.setCreated(System.currentTimeMillis());
        mongoTemplate.save(album,albumDbName + publish.getUserId());

        //3、查询好友的时间线表
        Query query = Query.query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> users = mongoTemplate.find(query,Friend.class);

        //4、查询当前用户的好友数据，将动态数据写入到好友的时间线表中
        for (Friend user : users) {
            TimeLine timeLine = new TimeLine();
            timeLine.setUserId(publish.getUserId());
            timeLine.setPublishId(publish.getId());
            timeLine.setId(ObjectId.get());
            timeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(timeLine,timelineDbName+publish.getUserId());
        }
    }

    @Override
    public Movements findById(String id) {

        Publish publish = this.mongoTemplate.findById(new ObjectId(id), Publish.class);

        Movements movements = new Movements();

        BeanUtils.copyProperties(publish, movements);
        movements.setId(id);
        UserInfo info = infoMapper.selectById(publish.getUserId());
        BeanUtils.copyProperties(info, movements);
        movements.setTags(info.getTags().split(","));
        //是否点赞
        movements.setHasLiked(1); //是否点赞
        //是否喜欢
        movements.setHasLoved(0); //是否喜欢

        movements.setDistance("1.2公里"); //TODO 距离
        movements.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated()))); //发布时间，10分钟前
        movements.setImageContent(publish.getMedias().toArray(new String[]{}));
        return movements;
    }


    @Override
    public PageResult findAll(int page, int size,Long userId,int type) {

        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Order.desc("created")));

        Query query = new Query().with(pageable);

        List<Album> pids = new ArrayList<>();

        Long count = 0l;

        if(type == 0) {
            pids =  mongoTemplate.find(query, Album.class,albumDbName+userId);
            count = mongoTemplate.count(new Query(), Album.class, albumDbName + userId);
        }else if (type == 1) {
            pids =  mongoTemplate.find(query, Album.class,timelineDbName+userId);
            count = mongoTemplate.count(new Query(), Album.class, timelineDbName + userId);
        }else if(type==2) {
            query.addCriteria(Criteria.where("userId").is(userId));
            pids =  mongoTemplate.find(query, Album.class,"recommend_quanzi");
            count = mongoTemplate.count(new Query(), Album.class, "recommend_quanzi");
        }

        //查询相册所对应的动态信息
        List<Movements> movementsList = new ArrayList<>();

        for (Album album : pids) {
            Publish publish = this.mongoTemplate.findById(album.getPublishId(), Publish.class);
            Movements movements = new Movements();
            BeanUtils.copyProperties(publish, movements);
            movements.setId(publish.getId().toString());
            //是否喜欢
            UserInfo info = infoMapper.selectById(publish.getUserId());
            BeanUtils.copyProperties(info, movements);
            movements.setTags(info.getTags().split(","));
            movements.setHasLiked(1); //是否点赞
            movements.setHasLoved(0); //是否喜欢
            movements.setDistance("1.2公里"); //TODO 距离
            movements.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated()))); //发布时间，10分钟前
            movements.setImageContent(publish.getMedias().toArray(new String[]{}));
            movementsList.add(movements);
        }

        return new PageResult(page,size,count.intValue(),movementsList);
    }


}
